//让node能连接mysql
const mysql = require('mysql')  //引入mysql包
const config = require('../config/mySqlConfign.js')


//创建线程池, 连接本地的mysql库
const pool = mysql.createPool({
  host: config.database.HOST,
  user: config.database.USERNAME,
  password: config.database.PASSWORD,
  database: config.database.DATABASE,
  port: config.database.PORT
})


//连接数据库，执行sql语句
const allService = {
  // 当有人调用我的自己定义query方法时
  query: function (sql, values) {
    return new Promise((resolve, reject) => {
      pool.getConnection((err, connection) => {  //连接数据库
        if (err) {
          reject(err)
        } else {  //连接成功
          connection.query(sql, values, (err, rows) => {  //执行sql语句的,query本地的方法
            if (err) {
              reject(err)
            } else { //sql语句执行成功
              resolve(rows)  //存在返回这个数据 用户名 密码
            }
            connection.release()  //断开连接
          })
        }
      })
    })
  }
}

//登录
const userLogin = (username, password) => {  //我们传的值
  //选择这张表的所有数据  是否存在 usersname=username  pasword=password
  let _sql = `select * from users where username="${username}" and password="${password}";`

  return allService.query(_sql)
}

//查找数据库数据
const userFind=(username)=>{
  let _sql=`select * from users where username="${username}";`
  return allService.query(_sql)

}

//注册，
const userRegister=(values)=>{

  let _sql=`insert into users set username=?,password=?,nickname=?;`
  return allService.query(_sql,values)
} 
module.exports = {
  userLogin,userFind,userRegister
}